package com.jiezheng.huinong.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.jiezheng.huinong.biz.ExportFile;
import com.jiezheng.huinong.biz.ZipFileHelper;
import com.jiezheng.huinong.model.ApplyInfo;
import com.opensymphony.xwork2.ActionSupport;

public class ApplyDownloadAction extends ActionSupport {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -1524426599132265333L;

	// 所有的指标信息
	private ApplyInfo apply = new ApplyInfo();

	// 所有的申请ID列表
	private String idList = "";

	private String fileName = "";

	private static final String TMPLATE_PATH = "template/";
	private static final String DEST_FILE_NAME = "ShenQingXiangQing.zip";

	public String downloadApply() {

		String[] idCards = idList.split("[:]");
		int size = idCards.length;
		if (size < 1) {
			return NONE;
		}

		// 待压缩的文件路径
		String srcFilePath = getFilePath() + "//" + "ShenQingXiangQing";
		File srcFile = new File(srcFilePath);
		srcFile.mkdirs();
		

		for (int i = 0; i < size; i++) {
			String applyNo = idCards[i];
			if (applyNo != null && !applyNo.isEmpty()) {
				String fileName = String.format("%s.xls", applyNo);
				String filePath = srcFilePath + "//" + fileName;
				ExportFile.exportZhiFuFile(applyNo, filePath, fileName);
			}
		}

		// 目标文件名与路径
		String destFileName = DEST_FILE_NAME;
		String destFilePath = getFilePath() + "//" + destFileName;
		File destFile = new File(destFilePath);
		if(destFile.exists()){
			destFile.delete();
		}

		try {
			ZipFileHelper.compress(srcFile, destFile);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("文件压缩失败!");
		}
		
		if(srcFile.exists()){
			try {
				FileUtils.deleteDirectory(srcFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		this.setFileName(destFileName);
		return SUCCESS;
	}

//	private String getLoninId() {
//		Map<String, Object> session = ActionContext.getContext().getSession();
//		String loginId = (String) session.get("loginId");
//		return loginId;
//	}

	public ApplyInfo getApply() {
		return apply;
	}

	public void setApply(ApplyInfo apply) {
		this.apply = apply;
	}

	public String getIdList() {
		return idList;
	}

	public void setIdList(String idList) {
		this.idList = idList;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFilePath() {
		return ServletActionContext.getServletContext().getRealPath(
				TMPLATE_PATH);
	}

}
